
<template>
  <div>
    <el-dialog
      title="提示"
      :visible.sync="isOpen"
      width="30%"
      :before-close="handleClose"
    >
<!--   分页   -->
      <el-tree
        :data="data"
        show-checkbox
        default-expand-all
        node-key="id"
        :default-expanded-keys="init"
        :default-checked-keys="init"
        :props="defaultProps"
        @check="clickNode"
      >
      </el-tree>

      <span slot="footer" class="dialog-footer">
        <el-button @click="open('取消修改','warning');isOpen = false">取消</el-button>
      <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import { GET_ALL_PERMISSION, GET_ALL_ROLE } from '@/store/role/CONST'
import { roleChildren } from '@/components/roles/Roles.vue'
import { updateRole } from '@/api/permission'

@Component
export default class AssignRoles extends Vue {
  public isOpen = false
  public data = []

  public init:Array<number> = []

  public currentSelectArr:Array<number> = []
  public currentId = 0

  // 子节点参数
  public defaultProps = {
    children: 'children',
    label: 'authName'
  }

  handleClose (done:any) {
    this.$confirm('确认关闭？')
      .then(_ => {
        done()
      })
      .catch(_ => {
        //
      })
  }

  enter (id:number, children:Array<roleChildren>) {
    this.isOpen = true
    this.currentId = id
    this.init = []
    this.initDefault(children)
  }

  clickNode (_:unknown, data:any) {
    this.currentSelectArr = data.checkedKeys
  }

  initDefault (children:Array<roleChildren>) {
    children.forEach(item => {
      this.init.push(item.id)
      if (item.children instanceof Array) this.initDefault(item.children)
    })
  }

  async submit () {
    if (!this.currentSelectArr.length) return this.open('未作出修改', 'warning')
    this.isOpen = false
    const { meta: { status, msg } } = await updateRole(this.currentId, this.currentSelectArr)
    this.open(msg, status === 200 ? 'success' : 'error')
    this.$emit('toRender')
  }

  open (
    smg = '登陆成功',
    type: 'success' | 'warning' | 'info' | 'error' = 'success'
  ) {
    this.$message({
      message: smg,
      type: type
    })
  }

  created () {
    this.getAllPermission()
  }

  async getAllPermission () {
    await this.$store.dispatch('role/' + GET_ALL_PERMISSION)
    this.$nextTick(() => {
      this.data = this.$store.state.role.permission
    })
  }
}
</script>
